package com.example.userservice.controller;

import com.example.userservice.common.R;
import com.example.userservice.dto.*;
import com.example.userservice.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    @PostMapping("/user/register")
    public R<UserResponse> register(@RequestBody UserRegistrationRequest registrationRequest) {
        UserResponse userResponse = userService.register(registrationRequest);
        return R.success(userResponse);
    }

    @PostMapping("/user/login")
    public R<JwtResponse> login(@RequestBody LoginRequest loginRequest) {
        String token = userService.login(loginRequest);
        return R.success(new JwtResponse(token));
    }

    @GetMapping("/users")
    @PreAuthorize("isAuthenticated()")
    public R<List<UserResponse>> getAllUsers() {
        return R.success(userService.getAllUsers());
    }

    @GetMapping("/user/{userId}")
    @PreAuthorize("isAuthenticated()")
    public R<UserResponse> getUserById(@PathVariable("userId") Long userId) {
        return R.success(userService.getUserById(userId));
    }

    @PutMapping("/user/{userId}")
    @PreAuthorize("isAuthenticated() and #userId == #userId")
    public R<UserResponse> updateUser(@PathVariable("userId") Long userId, @RequestBody UserRegistrationRequest request) {
        return R.success(userService.updateUser(userId, request));
    }

    @PostMapping("/user/reset-password")
    @PreAuthorize("isAuthenticated()")
    public R<Void> resetPassword(@RequestBody ResetPasswordRequest request) {
        userService.resetPassword(request.getUserId(), request.getNewPassword());
        return R.success();
    }
} 